﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace WindowsFormsApp1
{
  public partial class Form1 : Form {
    private NotifyIcon notifyIcon;
    private Icon icon1;
    private Icon icon2;
    private Timer blinkTimer;
    private bool isIcon1 = true;

    public Form1() {
      InitializeComponent();

      // 加载两个不同的图标
      icon1 = new Icon("shell32_155.ico");
      icon2 = new Icon("shell32_161.ico");

      // 创建 NotifyIcon 控件
      notifyIcon = new NotifyIcon();
      notifyIcon.Icon = icon1;
      notifyIcon.Visible = true;
      notifyIcon.Text = "我的应用程序";
      notifyIcon.MouseClick += NotifyIcon_MouseClick;
      notifyIcon.ContextMenuStrip = contextMenuStrip1;

      // 创建定时器
      blinkTimer = new Timer();
      blinkTimer.Interval = 500; // 每 500 毫秒切换一次图标
      blinkTimer.Tick += BlinkTimer_Tick;
      blinkTimer.Start();

      this.Hide();
    }

    private void NotifyIcon_MouseClick(object sender, MouseEventArgs e) {
      // 鼠标左键点击
      if (e.Button == MouseButtons.Left) {
        // 如果窗体当前是隐藏状态，则显示并激活窗体
        if (!this.Visible) {
          this.Show();
          this.WindowState = FormWindowState.Normal;
          this.Activate();
        }
        // 如果窗体当前是显示状态，则最小化到托盘
        else {
          this.WindowState = FormWindowState.Minimized;
          this.Hide();
        }
      }
    }

    private void BlinkTimer_Tick(object sender, EventArgs e) {
      if (isIcon1) {
        notifyIcon.Icon = icon2;
      }
      else {
        notifyIcon.Icon = icon1;
      }
      isIcon1 = !isIcon1;
    }

    protected override void OnFormClosing(FormClosingEventArgs e) {
      base.OnFormClosing(e);
      // 释放资源
      notifyIcon.Visible = false;
      notifyIcon.Dispose();
      icon1.Dispose();
      icon2.Dispose();
      blinkTimer.Stop();
      blinkTimer.Dispose();
    }

    private void Form1_FormClosing(object sender, FormClosingEventArgs e) {
      // 判断是否是用户点击了关闭按钮（X）
      if (e.CloseReason == CloseReason.UserClosing) {
        
        // 取消关闭操作
        e.Cancel = true;
      }
    }

    private void Form1_Load(object sender, EventArgs e) {
      this.Hide();
      this.ShowInTaskbar = false;

    }

    private void 退出ToolStripMenuItem_Click(object sender, EventArgs e) {
      // 释放资源
      notifyIcon.Visible = false;
      notifyIcon.Dispose();
      icon1.Dispose();
      icon2.Dispose();
      blinkTimer.Stop();
      blinkTimer.Dispose();
      Application.Exit();
    }
  }
}
